import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/bindPhone', '/userAgreement', '/privacyPolicy']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  const { meta = {} } = to;
  if (!meta.doNotSetTitle && meta.title) {
    document.title = meta.title;
  }
  next()
  return
  // determine whether the user has logged in
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === '/login' || to.path === '/bindPhone') {
      // if is logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done(); // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      const hasRelevantInfo = Object.keys(store.getters.relevantInfo).length > 0;
      console.log('hasRelevantInfo', hasRelevantInfo, store.getters.relevantInfo);
      let plotProgress = store.getters.plotProgress;
      if (plotProgress == -1) {
        await store.dispatch('getPlotProgress');
        plotProgress = store.getters.plotProgress;
      }
      if (plotProgress != 2 && process.env.NODE_ENV !== 'development') {
        window.location.href = '/plot/choosegender.html';
      }
      if (hasRelevantInfo) {
        next();
      } else {
        await store.dispatch('getRelevantInfo');
        next();
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
